<template>
  <div class="app-container">
    <el-card class="operate-container" shadow="never">
      <el-form :inline="true">
        <el-form-item label="您所需要查看的门店商品信息！">
        </el-form-item>
      </el-form>
      <el-form :inline="true" v-show="this.flag === 'business'">
        <el-button @click="handleCreate" type="success" icon="el-icon-plus" circle></el-button>
      </el-form>
      <el-form :inline="true" v-show="this.flag === 'customer'">
        <el-button style="margin-left: 1400px" type="warning" @click="settlement">结算</el-button>
      </el-form>
    </el-card>
    <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
    >
      <el-table-column align="center" label="序号" width="130">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="商品名称" width="300" align="center">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="商品图片" width="300" align="center">
        <template slot-scope="scope">
          <el-image
              style="width: 200px; height: 150px"
              :src="'http://localhost:8080'+scope.row.image"
              :preview-src-list="srcList"
              @click="vbs(scope.row.image)"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="商品单价" width="100" align="center">
        <template slot-scope="scope">
          ￥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="商品描述" width="390" align="center">
        <template slot-scope="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="商品状态" width="auto" align="center" v-if="flag === 'business'">
        <template slot-scope="scope">
          <el-button v-show="scope.row.upordown === 'down'" type="danger">商品未上线</el-button>
          <el-button v-show="scope.row.upordown === 'up'" type="success">商品已上线</el-button>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="小计" width="auto" align="center" v-if="flag === 'customer'">
        <template slot-scope="scope">
          ￥{{ scope.row.amount = parseFloat(scope.row.price * (isNaN(scope.row.num) ? 0 : scope.row.num)).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="auto" align="center" v-if="flag === 'business'">
        <template slot-scope="scope">
          <el-button type="success"
                     v-show="scope.row.upordown === 'down' && flag === 'business'"
                     @click="upDownMethod(scope.row.id,scope.row.upordown)"
          >
            上线
          </el-button>
          <el-button type="danger"
                     v-show="scope.row.upordown === 'up' && flag === 'business'"
                     @click="upDownMethod(scope.row.id,scope.row.upordown)"
          >
            下线
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="数量" width="auto" align="center" v-if="flag === 'customer'">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.num"
                           size="small"
                           :min="0"
                           :max="999"
                           v-show="flag === 'customer'"
                           @change=""
                           label="0"
          >
          </el-input-number>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        :current-page="page"
        :total="total"
        :page-size="size"
        :page-sizes="[5, 10, 15, 20, 25, 30, 100]"
        style="padding: 30px 0; text-align: center;"
        layout="sizes, prev, pager, next, jumper, ->, total, slot"
        @current-change="fetchData"
        @size-change="changeSize"
        v-show="flag === 'business'"
    />
    <el-dialog :visible.sync="dialogFormVisible" title="创建新商品">
      <el-form
          :model="item"
          label-position="left"
          label-width="90px"
          style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="item.name"></el-input>
        </el-form-item>
        <el-form-item label="商品图片" prop="image">
          <div class="hello">
            <el-upload
                class="avatar-uploader"
                action="http://localhost:8080/item/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" alt=""/>
              <i v-else class="el-icon-upload2 avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="item.price"/>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input v-model="item.description"/>
        </el-form-item>
        <el-form-item label="商品状态" prop="upordown">
          <el-switch
              v-model="upOrDown"
              active-color="#13ce66"
              inactive-color="#ff4949"
              disabled
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="restForm">取消</el-button>
        <el-button type="primary" @click=" createData">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogFormVisibleTow"
               :before-close="handleDialogClose"
               title="结算商品"
    >
      <el-table
          v-loading="listLoading"
          :data="settlementList"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
      >
        <el-table-column align="center" label="序号" width="69">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="商品名称" width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="商品图片" width="300" align="center">
          <template slot-scope="scope">
            <el-image
                style="width: 120px; height: 80px"
                :src="'http://localhost:8080'+scope.row.image"
                :preview-src-list="srcList"
                @click="vbs(scope.row.image)"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column class-name="status-col" label="商品单价" width="100" align="center">
          <template slot-scope="scope">
            ￥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column class-name="status-col" label="小计" width="100" align="center">
          <template slot-scope="scope">
            ￥{{
              scope.row.amount = parseFloat(scope.row.price * (isNaN(scope.row.num) ? 0 : scope.row.num)).toFixed(2)
            }}
          </template>
        </el-table-column>
        <el-table-column label="数量" width="auto" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.num"
                             size="small"
                             :min="0"
                             :max="999"
                             @change=""
                             label="0"
                             :disabled="true"
            >
            </el-input-number>
          </template>
        </el-table-column>
      </el-table>
      <el-col :span="8">
        <el-card shadow="never">
          总计：<span>￥{{
            totalPrice =
                parseFloat(settlementList.reduce((sum, e) => sum + Number(e.amount || 0), 0)).toFixed(2)
          }}</span>
        </el-card>
      </el-col>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="createOrder">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { addItem, getList, updateItemUpOrDown } from '@/api/tree'
import { addOrder } from '@/api/order'

export default {
  computed: {},
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      settlementList: [],
      listLoading: true,
      item: {},
      page: 1,
      size: 5,
      total: 0,
      srcList: [],
      flag: '',
      dialogFormVisible: false,
      dialogFormVisibleTow: false,
      imageUrl: '',
      upOrDown: false,
      shopId: '',
      upordown: '',
      num: 0,
      amount: '',
      totalPrice: ''
    }
  },
  created() {
    this.viewByTokenFlag()
    this.fetchData()
  },
  methods: {
    // 当页码发生改变的时候
    changeSize(size) {
      this.size = size
      this.fetchData(1)
    },
    // 查询商品
    fetchData(page = 1) {
      this.page = page
      this.listLoading = true
      this.shopId = this.$route.query.id
      let userId = JSON.parse(getToken()).id
      if (this.flag === 'customer') {
        this.size = 2147483647
      }
      getList(this.page, this.size, userId, this.shopId).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    // 根据角色展示不同视图
    viewByTokenFlag() {
      let token = getToken()
      let parseToken = JSON.parse(token)
      this.flag = parseToken.flag
    },
    // 点击预览大图
    vbs(val) {
      this.srcList = []
      val = 'http://localhost:8080' + val
      this.srcList.push(val)
    },
    // 创建弹出
    handleCreate() {
      this.item = {}
      this.dialogFormVisible = true
    },
    // 重置添加表单
    restForm() {
      this.dialogFormVisible = false
      this.imageUrl = ''
    },
    // 添加商品
    createData() {
      let token = getToken()
      this.item.userId = JSON.parse(token).id
      this.item.upordown = 'down'
      this.item.shopId = this.shopId
      addItem(this.item).then(response => {
        this.dialogFormVisible = false
        this.$message({
          message: '添加成功',
          type: 'success'
        })
        this.fetchData()
      }).catch(() => {
        this.$message.error('出现故障，添加失败！')
        this.dialogFormVisible = false
      })
    },
    // 上传
    handleAvatarSuccess(res, file) {
      this.item.image = res.toString().split('resources')[1]
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    // 校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 上下线商品
    upDownMethod(itemId, flag) {
      updateItemUpOrDown(itemId, flag).then(response => {
        this.$message({
          message: '商品操作成功！',
          type: 'success'
        })
        this.fetchData()
      }).catch(() => {
        this.$message.error('出现故障，添加失败！')
      })
    },
    // 结算
    settlement() {
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].num > 0) {
          this.settlementList.push(this.list[i])
        }
      }
      if (this.settlementList.length !== 0) {
        this.dialogFormVisibleTow = true
      } else {
        this.$message({
          showClose: true,
          message: '请选择您需要的商品！',
          type: 'warning'
        })
      }
    },
    // 清除结算dialog框
    handleDialogClose() {
      this.dialogFormVisibleTow = false
      this.settlementList = []
      this.fetchData(1)
    },
    // 创建订单
    createOrder() {
      let token = getToken()
      this.settlementList.forEach(s => s.userId = JSON.parse(token).id)
      console.log(this.settlementList)
      addOrder(this.settlementList, this.totalPrice).then(response => {
        this.handleDialogClose()
        this.$message({
          showClose: true,
          message: '结算完毕，请至订单界面付款！',
          type: 'success'
        })
      }).catch(() => {
      })
    }
  }
}
</script>
<style>
.time {
  font-size: 13px;
  color: #999;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 100%;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}
</style>
